using FytSoa.Application.Erp.Param;
using FytSoa.Domain.Erp;
using FytSoa.Sugar;
using FytSoa.Common.Utils;
using FytSoa.Common.Param;
using FytSoa.Common.Result;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FytSoa.Application.Erp;

/// <summary>
/// erp-盘点单表服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "v9")]
public class ErpTakestockOrderService : IApplicationService 
{
    private readonly SugarRepository<ErpTakestockOrder> _thisRepository;
    private readonly SugarRepository<ErpTakestockDetail> _detailRepository;
    private readonly SugarRepository<ErpWarehouseProduct> _inventoryRepository;
    public ErpTakestockOrderService(SugarRepository<ErpTakestockOrder> thisRepository
        ,SugarRepository<ErpWarehouseProduct> inventoryRepository
    ,SugarRepository<ErpTakestockDetail> detailRepository)
    {
        _thisRepository = thisRepository;
        _inventoryRepository = inventoryRepository;
        _detailRepository = detailRepository;
    }
    
    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<ErpTakestockOrderDto>> GetPagesAsync(PageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .Includes(m=>m.TypeObj)
            .Includes(m=>m.OperationObj)
            .Includes(m=>m.WarehouseObj)
            .OrderByDescending(m=>m.Id)
            .ToPageAsync(param.Page, param.Limit);
        return query.Adapt<PageResult<ErpTakestockOrderDto>>();
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ErpTakestockOrderDto> GetAsync(long id)
    {
        var model = await _thisRepository.GetByIdAsync(id);
        return model.Adapt<ErpTakestockOrderDto>();
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task AddAsync(ErpTaskStockOrderParam model)
    {
        var order = model.Adapt<ErpTakestockOrder>();
        var toDay = await _thisRepository.CountAsync(m=>SqlFunc.DateIsSame(m.CreateTime,DateTime.Now));
        order.Number = "P".ResNumber(toDay);
        order.OperationId = AppUtils.LoginId;
        var orderId=await _thisRepository.InsertReturnSnowflakeIdAsync(order);
        var detailList = new List<ErpTakestockDetail>();
        foreach (var item in model.Product)
        {
            detailList.Add(new ErpTakestockDetail()
            {
                OrderId = orderId,
                ProductId = item.Id,
                SourceCount = item.SourceStock,
                NewCount = item.CheckStock,
                PAL=item.PAL,
            });
        }

        await _detailRepository.InsertRangeAsync(detailList);
    }

    /// <summary>
    /// 执行，并修改库存
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task ModifyExecuteAsync(List<long> id)
    {
        var orderId = id[0];
        var order = await _thisRepository.GetByIdAsync(orderId);
        var detailList = await _detailRepository.GetListAsync(m => m.OrderId==orderId);
        var productIds = detailList.Select(m => m.ProductId).GroupBy(m => m)
            .Select(m=>m.Key).ToList();

        var inventoryList = await _inventoryRepository.GetListAsync(m => m.WarehouseId==order.WarehouseId && productIds.Contains(m.ProductId));
        foreach (var item in inventoryList)
        {
            var detail = detailList.FirstOrDefault(m => m.ProductId == item.ProductId);
            if(detail==null) continue;
            item.Count = detail.NewCount;
        }
        await _inventoryRepository.UpdateRangeAsync(inventoryList);

        await _thisRepository.AsUpdateable().SetColumns(m => m.Status == true)
            .Where(m => m.Id==orderId)
            .ExecuteCommandAsync();
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> ModifyAsync(ErpTakestockOrderDto model) =>
        await _thisRepository.UpdateAsync(model.Adapt<ErpTakestockOrder>());

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete,UnitOfWork]
    public async Task DeleteAsync([FromBody] List<long> ids)
    {
        await _thisRepository.DeleteAsync(m=>ids.Contains(m.Id));
        await _detailRepository.DeleteAsync(m => ids.Contains(m.OrderId));
    }
}
